
package com.wceManage.manage.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.wceManage.beans.SysRole;
import com.wceManage.beans.SysUser;
import com.wceManage.beans.page.PageList;
import com.wceManage.commons.PwdUtils;
import com.wceManage.commons.util.StringUtil;
import com.wceManage.manage.util.UserUtils;
import com.wceManage.services.SysRoleService;
import com.wceManage.services.SysUserService;

@Controller
@RequestMapping("systemUser")
public class SystemUserController extends BaseController {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleService sysRoleService;

	

	@ModelAttribute("sysUser")
	public SysUser get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return UserUtils.get(id);
		} else {
			return new SysUser();
		}
	}

	/**
	 * 查询列表
	 *
	 * @param sysUser
	 * @return
	 */
	@RequiresPermissions("sys:systemUser:view")
	@RequestMapping(value = { "", "/", "list" })
	public String list(SysUser sysUser, HttpServletRequest request)
			throws InstantiationException, IllegalAccessException {
		request.setAttribute("sysUser", sysUser);

		return "sys/systemUser/list";
	}

	/**
	 * 异步获取list资源
	 *
	 * @param pageList
	 * @param sysUser
	 * @return
	 */
	@RequiresPermissions("sys:systemUser:view")
	@RequestMapping("asynList")
	@ResponseBody
	public PageList asynList(PageList pageList, SysUser sysUser) {
		sysUser.setUserType(0);
		PageList<SysUser> pagelist=sysUserService.queryPage(pageList, sysUser);
		List<SysUser> sysUserList=pagelist.getAaData();
		for (SysUser sysUser2 : sysUserList) {
			sysUser2.setUserRole(sysRoleService.findRoleByUserId(sysUser2.getUserId().toString()).get(0).getName());
		}
		return pagelist;
	}

	/**
	 * 新增修改
	 *
	 * @param sysUser
	 * @return
	 */
	@RequiresPermissions("sys:systemUser:edit")
	@RequestMapping(value = { "add", "edit" }, method = RequestMethod.GET)
	public String edit(SysUser sysUser, Model model) {

		if (sysUser.getUserId() == null || sysUser.getUserId() < 1l) { // add
			sysUser = new SysUser();
		} else {
			sysUser = sysUserService.queryById(sysUser.getUserId());
		}

		model.addAttribute("sysUser", sysUser);

		List<SysRole> rlist = new ArrayList<>();
		rlist.addAll(sysRoleService.queryList(new SysRole()));
		model.addAttribute("allRoles", rlist);

		return "sys/systemUser/edit";
	}

	/**
	 * 修改
	 *
	 * @param userId
	 * @return
	 */
	@RequiresPermissions("sys:systemUser:edit")
	@RequestMapping(value = "modify", method = RequestMethod.GET)

	public String modify(Long userId, Model model) {

		SysUser sysUser = sysUserService.queryById(userId);

		model.addAttribute("sysUser", sysUser);

		List<SysRole> rlist = new ArrayList<>();
		rlist.addAll(sysRoleService.queryList(new SysRole()));
		model.addAttribute("allRoles", rlist);

		return "sys/systemUser/edit";
	}

	@RequiresPermissions("sys:systemUser:edit")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(SysUser sysUser) {
		sysUser.setUpdateBy(UserUtils.getUser().getUserId());
		// 如果新密码为空，则不更换密码
		if (StringUtil.isNotBlank(sysUser.getPassword())) {
			if (sysUser.getSalt() == null || sysUser.getSalt().isEmpty()) {
				sysUser.setSalt(PwdUtils.getSalt());
			}
			sysUser.setPassword(PwdUtils.saltPwd(sysUser.getPassword(), sysUser.getSalt()));
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<SysRole> roleList = Lists.newArrayList();
		List<Long> roleIdList = sysUser.getRoleIdList();
		for (SysRole r : UserUtils.getRoleList()) {
			if (roleIdList.contains(r.getRoleId())) {
				roleList.add(r);
			}
		}

		sysUser.setRoleList(roleList);
		sysUser.setPhone(sysUser.getAccount());
		if (sysUser.getUserId() == null) {
			sysUser.setUserType(0);
			sysUser.setParent(0L);
			sysUserService.add(sysUser);
		} else {
			sysUserService.update(sysUser);
			// 清除老的用户与角色关联
			sysUserService.deleteUserRole(sysUser);
		}
		// 保存用户与角色关联
		if (sysUser.getRoleList() != null && sysUser.getRoleList().size() > 0) {
			sysUserService.insertUserRole(sysUser);
		}

		UserUtils.clearCache(sysUser);
		// 清除当前用户缓存
		if (sysUser.getAccount().equals(UserUtils.getUser().getAccount())) {
			UserUtils.clearCache();
		}
		// TODO 成功失败结果页面
		return "redirect:list";
	}

	@RequiresPermissions("sys:systemUser:edit")
	@RequestMapping("delete")
	@ResponseBody
	public Object delete(Long id, HttpServletRequest request) {
		SysUser sysUser = new SysUser();
		sysUser.setUserId(id);
		sysUser.setUpdateBy(UserUtils.getUser().getUserId());
		sysUser.setStatus(1);
		int result = sysUserService.delete(sysUser);
		return result;
	}

	@RequestMapping("detail")
	public String detail(Long id, HttpServletRequest request) {
		SysUser sysUser = sysUserService.queryDetail(id);

		request.setAttribute("sysUser", sysUser);
		request.setAttribute("pName", sysUser.getpName());
		request.setAttribute("salespersonName", sysUser.getSalespersonName());
		request.setAttribute("salespersonPhone", sysUser.getSalespersonPhone());

		Map rewardTicketCountMap = new HashMap();

		Map map = new HashMap();
		map.put("phone", sysUser.getAccount());
		map.put("status", "");

		

		return "sys/systemUser/detail";
	}

	@RequiresPermissions("sys:systemUser:edit")
	@RequestMapping("thaw")
	@ResponseBody
	public Object thaw(Long id, HttpServletRequest request) {
		SysUser sysUser = new SysUser();
		sysUser.setUserId(id);
		sysUser.setUpdateBy(UserUtils.getUser().getUserId());
		sysUser.setStatus(0);
		int result = sysUserService.delete(sysUser);
		// TODO 成功失败结果页面
		return result;
	}

	/**
	 * 验证登录名是否有效
	 *
	 * @param oldAccount
	 * @param mobile
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:systemUser:edit")
	@RequestMapping(value = "checkAccount", method = RequestMethod.POST)
	public Boolean checkAccount(String oldAccount, String mobile) {
		if (mobile != null && mobile.equals(oldAccount)) {
			return Boolean.TRUE;
		} else if (mobile != null && sysUserService.queryUserByAccount(mobile) == null) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
	
	
	@RequiresPermissions("sys:systemUser:edit")
	@RequestMapping("initPass")
	@ResponseBody
	public Object initPass(Long id, HttpServletRequest request) {
		
		SysUser sysUser = sysUserService.queryById(id);
		HashMap<String, String> param=new HashMap<String,String>();
		param.put("password", PwdUtils.saltPwd("000000", sysUser.getSalt()));
		param.put("account", sysUser.getAccount());
		int result = sysUserService.updateUserPwd(param);
		
		// TODO 成功失败结果页面
		return result;
	}
}
